package cate.game.role.pay.trademall.oncefund;

import cate.common.table.d.GDOperation;
import cate.common.table.trademall.oncefund.OnceFundCommonRow;
import cate.common.table.trademall.oncefund.OnceFundItemRow;
import cate.common.table.trademall.oncefund.OnceFundItemSheet;
import cate.common.util.GameResult;
import cate.game.chat.ChatContentParam;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.pay.trademall.oncefund.msg.OnceFundNormalRewardShowResp;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
@NoteClass(value = "交易坊-一次性基金")
public class OnceFundPO extends RoleDependent {
    @NoteField(value = "配置ID")
    public int tid;
    @NoteField(value = "类型")
    public int type;
    @NoteField(value = "是否已激活")
    public boolean active;
    @NoteField(value = "是否已结束")
    public boolean finished;
    @NoteField(value = "普通奖励领取状态")
    public Map<Integer, Boolean> normalGotMap;
    @NoteField(value = "目标值")
    public int targetValue;
    @NoteField(value = "期数")
    public int fundGroup;
    @NoteField(value = "结束时间")
    public long finishedTime;

    public OnceFundPO() {
    }

    public OnceFundPO(int tid, int type, int fundGroup) {
        this.tid = tid;
        this.type = type;
        this.fundGroup = fundGroup;
    }

    /**
     * 初始化
     */
    public void initialize(Role role) {
        super.initialize(role);
        if (normalGotMap == null) {
            normalGotMap = new HashMap<>();
        }
        // 数据兼容
        dataCheck();
        // 兼容完成后 判断是否要重新开启
        if (finished && !isAllGot()) {
            finished = false;
        }
    }

    /**
     * 数据兼容
     */
    private void dataCheck() {
        normalGotMap.entrySet().removeIf(entry -> {
            if (role.getGame().table.tradeMall.once_fund_item.get(entry.getKey()) == null) {
                return true;
            }
            return (role.getGame().table.tradeMall.once_fund_item.get(entry.getKey()).fundType != type)
                    ||(role.getGame().table.tradeMall.once_fund_item.get(entry.getKey()).fundGroup != fundGroup) ;
        });
        for (OnceFundItemRow configRow : role.getGame().table.tradeMall.once_fund_item.getList()) {
            if (configRow.fundType != type || configRow.fundGroup != fundGroup) {
                continue;
            }
            if (!normalGotMap.containsKey(configRow.id)) {
                normalGotMap.put(configRow.id, false);
            }
        }
    }

    /**
     * 是否全部领取
     */
    private boolean isAllGot() {
        List<OnceFundItemRow> rows = role.getGame().table.tradeMall.once_fund_item.getList();
        for (OnceFundItemRow configRow : rows) {
            if (configRow.fundType != type || configRow.fundGroup != fundGroup) {
                continue;
            }
            if (!normalGotMap.get(configRow.id)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检测是否结束
     */
    private void checkFinished() {
        if (finished) {
            return;
        }
        if (isAllGot()) {
            finished = true;
            finishedTime = now();
        }
    }

    /**
     * 是否可以激活高级基金
     *
     * @return 激活结果 无携带数据
     */
    public GameResult<Void> payAdvanceAllow() {
        GameResult<Void> r = new GameResult<>();
        if (active) {
            return r.fail("已激活该基金");
        }
        return r.success();
    }

    /**
     * 激活基金
     */
    public void activeFund() {
        if (active) {
            log.error("[OnceFundPO] 重复激活成长基金!!!");
            return;
        }
        OnceFundCommonRow commonRow = role.getGame().table.tradeMall.once_fund_common.get(tid);
        if (commonRow == null) {
            log.error("[OnceFundPO] 不存在的一次性基金!!!");
            return;
        }
        active = true;
        /*if (commonRow.mailId > 0 && commonRow.mailRewardStr != null && !commonRow.mailRewardStr.isEmpty()) {
            MixRes mailRes = new MixRes(commonRow.mailRewardStr);
            Mail activeMail = new MailBuilder().setReward(mailRes)
                    .setContentId(commonRow.mailId)
                    .build();
            role.getGame().mail.send(role, activeMail);
        }*/
        if (commonRow.lampId != 0) {
            List<ChatContentParam> params = new ArrayList<>();
            params.add(ChatContentParam.c(role.getBase().name));
            role.getGame().notice.lampOnline(role, commonRow.lampId, params);
        }
    }

    /**
     * 检测条件是否达成
     *
     * @param checkCondition 条件类型
     * @param value          数值
     * @return 是否检测通过
     */
    public boolean checkCondition(int checkCondition, int value) {
        switch (checkCondition) {
            case OnceFundItemSheet.ONCE_FUND_CHECK_CONDITION_LEVEL:
                return role.getBase().level >= value;
            case OnceFundItemSheet.ONCE_FUND_CHECK_CONDITION_MAIN_TOWER_LEVEL:
                return role.getFarm().tower.passedFloor >= value;
            case OnceFundItemSheet.ONCE_FUND_CHECK_CONDITION_POWER:
                return role.getBase().power >= value;
            default:
                log.error("[OnceFundPO] 未实现的检测条件！ " + checkCondition);
                return false;
        }
    }

    /**
     * 领取基金普通奖励
     *
     * @param configId 配置ID
     * @return 领取结果 无携带数据
     */
    public EcResult<Void> receiveNormalReward(int configId) {
        EcResult<Void> r = new EcResult<>();
        if (!active) {
            return r.fail("请先购买基金");
        }

        if (!normalGotMap.containsKey(configId)) {
            return r.fail("找不到该奖励");
        }
        if (normalGotMap.get(configId)) {
            return r.fail("该奖励已被领取");
        }
        OnceFundItemRow configRow = role.getGame().table.tradeMall.once_fund_item.get(configId);
        if (configRow == null) {
            return r.fail("配置错误");
        }
        if (!checkCondition(configRow.checkCondition, configRow.needValue)) {
            return r.fail("不满足领取条件");
        }
        MixRes mixRes = new MixRes(configRow.rewardStr);
        if (mixRes.isEmpty()) {
            return r.fail("配置错误 奖励为空");
        }
        EcResult<?> r_res = new MixResAdder().setRes(mixRes)
                .setOperation(GDOperation.TRADE_MALL_ONCE_FUND_NORMAL)
                .setOperationSub(configId)
                .setDialogReward(active)
                .exe(role);
        if (!r_res.ok()) {
            return r.fail(r_res.message);
        }
        if (!active) {
            role.sendNow(new OnceFundNormalRewardShowResp(configId, mixRes));
        }
        normalGotMap.put(configId, true);
        checkFinished();
        return r.success();
    }

    /**
     * 领取基金高级奖励
     *
     * @param configId 配置ID
     * @return 领取结果 无携带参数
     */
    public EcResult<Void> receiveAdvanceReward(int configId) {
        EcResult<Void> r = new EcResult<>();
        if (!active) {
            return r.fail("成长基金高级奖励尚未激活");
        }
        OnceFundItemRow configRow = role.getGame().table.tradeMall.once_fund_item.get(configId);
        if (configRow == null) {
            return r.fail("配置错误");
        }
        if (!checkCondition(configRow.checkCondition, configRow.needValue)) {
            return r.fail("不满足领取条件");
        }
        MixRes mixRes = new MixRes(configRow.rewardStr);
        if (mixRes.isEmpty()) {
            return r.fail("配置错误 奖励为空");
        }
        EcResult<?> r_res = new MixResAdder().setRes(mixRes)
                .setOperation(GDOperation.TRADE_MALL_ONCE_FUND_ADVANCE)
                .setOperationSub(configId)
                .setDialogReward(true)
                .exe(role);
        if (!r_res.ok()) {
            return r.fail(r_res.message);
        }
        //advanceGotMap.put(configId, true);
        checkFinished();
        return r.success();
    }

    /**
     * 一键领取基金奖励
     *
     * @return 领取结果 无携带数据
     */
    public EcResult<Void> oneClickReceiveReward() {
        EcResult<Void> r = new EcResult<>();
        MixRes totalRes = new MixRes();
        List<Integer> normalKeys = new LinkedList<>();
        normalGotMap.forEach((key, value) -> {
            if (value) {
                return;
            }
            OnceFundItemRow configRow = role.getGame().table.tradeMall.once_fund_item.get(key);
            if (configRow == null) {
                return;
            }
            if (checkCondition(configRow.checkCondition, configRow.needValue)) {
                normalKeys.add(key);
                totalRes.addList(new MixRes(configRow.rewardStr));
            }
        });
        if (totalRes.isEmpty()) {
            return r.fail("无可领取的奖励");
        }
        EcResult<?> r_res = new MixResAdder().setRes(totalRes)
                .setOperation(GDOperation.TRADE_MALL_ONCE_FUND_ONE_CLICK)
                .setOperationSub(0)
                .setDialogReward(true)
                .exe(role);
        if (!r_res.ok()) {
            return r.fail(r_res.message);
        }
        normalKeys.forEach(itemId -> normalGotMap.put(itemId, true));
        checkFinished();
        return r.success();
    }
}
